<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true">
      <el-form-item label="角色名称" prop="name">
        <el-input
          v-model="queryParams.roleName"
          placeholder="请输入角色名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="roleList">
      <el-table-column label="角色编号" prop="id" width="120" />
      <el-table-column label="角色标识" prop="name" :show-overflow-tooltip="true" width="150" />
      <el-table-column label="角色名称" prop="title" :show-overflow-tooltip="true" width="150" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope" v-if="scope.row.id !== 1">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
          <!-- <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="100px">
        <el-form-item label="角色标识" prop="name">
          <el-input v-model="roleForm.name" placeholder="请输入角色标识" />
        </el-form-item>
        <el-form-item label="角色名称" prop="title">
          <el-input v-model="roleForm.title" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="菜单权限">
          <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event)">展开/折叠</el-checkbox>
          <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event)">全选/全不选</el-checkbox>
          <el-checkbox v-model="roleForm.deptCheckStrictly" @change="handleCheckedTreeConnect($event)">父子联动</el-checkbox>
          <el-tree class="tree-border" :data="menuOptions" show-checkbox ref="menu" node-key="id" :check-strictly="!roleForm.menuCheckStrictly" empty-text="加载中，请稍候" :props="defaultProps" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRole, delRole, addRole, updateRole, addPerm, updatePerm, getPerm } from "@/api/system/role";
import { listMenu, treeselect } from "@/api/system/menu";

export default {
  name: "Role",
  data() {
    return {
      loading: true,
      menuList:[],
      total: 0,// 总条数
      roleList: [],// 角色表格数据
      title: "",// 弹出层标题
      open: false, // 是否显示弹出层
      menuExpand: false,
      menuNodeAll: false,
      menuOptions: [],// 菜单列表
      queryParams: { // 查询参数
        pageNum: 1,
        pageSize: 10,
        name: undefined,
      },
      roleForm: {},// 表单参数
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: "角色名称不能为空", trigger: "blur" }
        ],
        title: [
          { required: true, message: "角色说明不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getAllmenu()
  },
  methods: {
    /** 查询角色列表 */
    getList() {
      this.loading = true;
      listRole(this.queryParams).then(response => {
          this.roleList = response.data;
          this.total = response.data.length
          this.loading = false
        }
      );
    },
     /** 查询菜单列表 */
    getAllmenu(){
      listMenu().then(res => {
        this.menuList = res.data
      });
    },
    /** 查询菜单树结构 */
    getMenuTreeselect() {
      treeselect().then(res => {
        const data = res.data
        this.menuOptions = data.map(item => ({
          id: item.id,
          label: item.title,
          disabled: false,
          ...(item.children && {
            children: item.children.map(child => ({
              id: child.id,
              label: child.menuName,
              disabled: false
            }))
          })
        }))
      });
    },
    // 所有菜单节点数据
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      let checkedKeys = this.$refs.menu.getCheckedKeys();
      // 半选中的菜单节点
      let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      if (this.$refs.menu != undefined) {
        this.$refs.menu.setCheckedKeys([]);
      }
      this.menuExpand = false,
      this.menuNodeAll = false,
      this.roleForm = {
        name:'',
        title:'',
        id:''
      };
      // this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 树权限（展开/折叠）
    handleCheckedTreeExpand(value) {
      let treeList = this.menuOptions;
      for (let i = 0; i < treeList.length; i++) {
        this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value;
      }
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value) {
      this.$refs.menu.setCheckedNodes(value ? this.menuOptions: []);
    },
    // 树权限（父子联动）
    handleCheckedTreeConnect(value) {
      this.roleForm.menuCheckStrictly = value ? true: false;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getMenuTreeselect();
      this.open = true;
      this.title = "添加角色";
    },
     /** 根据角色ID查询菜单树结构 */
     getRoleMenuTreeselect(name) {
      return getPerm({role_name:name}).then(response => {
        return response;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.getMenuTreeselect();
      const roleMenu = this.getRoleMenuTreeselect(row.name);
      this.$nextTick(() => {
        roleMenu.then(res => {
          this.reset();
          this.roleForm = row
          this.open = true;
          this.title = "修改角色";
          res.data.forEach(v => {
              this.$nextTick(()=>{
                this.$refs.menu.setChecked(v, true ,false);
              })
          })
        });
      });
    },
    filterMenu(){
      let ids = this.getMenuAllCheckedKeys()
      let perms =  ids.map(targetId => 
        this.menuList.find(item => item.id === targetId)?.perms
      )
      return perms
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["roleForm"].validate(valid => {
        if (valid) {
          const permParams = {
            role_name: this.roleForm.name,
            permission_names: this.filterMenu()
          }
          console.log(666,this.roleForm)
          if (this.roleForm.id) {
            updateRole(this.roleForm).then(response => {
              updatePerm(permParams).then(res => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              })
            });
          } else {
            addRole(this.roleForm).then(response => {
              addPerm(permParams).then(res => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              })
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const roleIds = row.roleId
      this.$modal.confirm('是否确认删除角色编号为"' + roleIds + '"的数据项？').then(function() {
        return delRole(roleIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
  }
};
</script>